import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { Local } from '/@/utils/storage';
import { formatAxis } from '/@/utils/formatTime';
import { NextLoading } from '/@/utils/loading';

export interface LoginState {
  loading: boolean;
}

type LoginEmit = (event: 'loading-change', value: boolean) => void;

export const useLogin = (ci: any) => {
  const router = useRouter();
  const state = ref<LoginState>({
    loading: false
  });

  // 登录成功后的处理
  const handleLoginSuccess = async (token: string, emit?: LoginEmit) => {
    try {
      state.value.loading = true;
      emit?.('loading-change', true);

      Local.set('token', token);
      const isNoPower = await initBackEndControlRoutes();

      if (isNoPower) {
        // 保存表格设置，避免被清除
        const tableSettings = localStorage.getItem('all-table-settings');
        Local.clear();
        // 恢复表格设置
        if (tableSettings) {
          localStorage.setItem('all-table-settings', tableSettings);
        }
        ElMessage.error('权限不足，请联系管理员');
        return false;
      }

      // 初始化登录成功时间问候语
      const currentTimeInfo = formatAxis(new Date());

      // 处理重定向
      if (router.currentRoute.value.query?.redirect) {
        router.push({
          path: <string>router.currentRoute.value.query?.redirect,
          query: Object.keys(<string>router.currentRoute.value.query?.params).length > 0
            ? JSON.parse(<string>router.currentRoute.value.query?.params)
            : '',
        });
      } else {
        router.push('/');
      }

      // 登录成功提示
      const signInText = ci.proxy.$t('message._admin.signInText');
      ElMessage.success(`${currentTimeInfo}，${signInText}`);

      // 添加 loading，防止第一次进入界面时出现短暂空白
      NextLoading.start();

      // 通知系统用户已登录
      try {
        const { useNotificationStore } = await import('/@/stores/notification');
        const notificationStore = useNotificationStore();
        notificationStore.onUserLogin();
      } catch (error) {
        console.warn('通知系统启动失败:', error);
      }

      return true;
    } catch (error) {
      console.error('登录处理失败:', error);
      ElMessage.error('登录失败，请稍后重试');
      return false;
    } finally {
      state.value.loading = false;
      emit?.('loading-change', false);
    }
  };

  return {
    state,
    handleLoginSuccess
  };
}; 